package com.dnjn.happiness.emo.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.domain.UserRecordTask;
import com.dnjn.happiness.emo.domain.UserRecordTaskTimeline;
import com.dnjn.happiness.emo.domain.vo.UserRecordTaskVO;
import com.dnjn.happiness.emo.service.IUserRecordTaskService;
import com.dnjn.happiness.emo.service.IUserRecordTaskTimelineService;
import com.dnjn.happiness.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 任务派发userRecordTaskController
 *
 * @author amber
 * @date 2024-01-12
 */
@Tag(name = "emo userRecordTask 任务派发userRecordTask", description = "任务派发userRecordTask")
@RestController
@RequestMapping("/userRecordTask")
public class UserRecordTaskController extends BaseController {
    @Autowired
    private IUserRecordTaskService userRecordTaskService;

    @Autowired
    private IUserRecordTaskTimelineService userRecordTaskTimelineService;

    /**
     * 查询任务派发userRecordTask列表
     */
    //@RequiresPermissions("emo:userRecordTask:list")
    @PostMapping("/list")
    @Operation(summary = "我发起的", description = "小程序-我的-我发起的,点击【发起任务】进入任务列表-参数userNameOrTaskContent-姓名或者内容-模糊查询")
    @Log(title = "emo", businessType = BusinessType.LIST)
    public AjaxResult list(@RequestParam(required = false) String userNameOrTaskContent, @RequestParam(defaultValue = "true") Boolean all, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Long userId = SecurityUtils.getUserId();
        if (all) {

            Page<UserRecordTaskVO> list = userRecordTaskService.listByAll(userNameOrTaskContent, userId, Page.of(current, size).addOrder(OrderItem.desc("task_id")));
            return success(list);
        } else {
            Page<UserRecordTaskVO> list = userRecordTaskService.listByAppraise(userNameOrTaskContent, userId, Page.of(current, size).addOrder(OrderItem.desc("task_id")));
            return success(list);
        }
    }


    @PostMapping("/listMyTask")
    @Operation(summary = "我的任务列表,待接收-A_APPLIED;待打卡-B_RECEIVED;待反馈-C_CHECKED_IN;待评价-D_FEEDBACK_GIVEN;已完成- F_DONE  ", description = "小程序-我的-我的-【我的任务】中可以查看;taskStatus -任务状态;taskContent-内容")
    @Log(title = "emo", businessType = BusinessType.LIST)
    public AjaxResult listMyTask(@RequestParam(required = false) String taskStatus, @RequestParam(required = false) String taskContent, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Long userId = SecurityUtils.getUserId();//当前登录用户

        Page<UserRecordTaskVO> list = userRecordTaskService.listByMy(taskStatus, taskContent, userId, Page.of(current, size).addOrder(OrderItem.desc("task_id")));
        return success(list);
    }

    /**
     * 获取任务派发userRecordTask详细信息
     */
    //@RequiresPermissions("emo:userRecordTask:query")
    @Operation(summary = "获取任务派发userRecordTask详细信息-发起人详情页", description = "点击引用原文也是调用该接口,把内容填上就可以")
    @GetMapping(value = "/{taskId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult get(@PathVariable("taskId") Long taskId) {
//        UserRecordTask vo = userRecordTaskService.getById(taskId);
        UserRecordTaskVO vo = userRecordTaskService.selectByTaskId(taskId, SecurityUtils.getUserId());
        if (null != vo) {
            List<UserRecordTaskTimeline> list = userRecordTaskTimelineService.lambdaQuery().eq(UserRecordTaskTimeline::getTaskId, taskId).eq(UserRecordTaskTimeline::getDeleted, "0").list();
            vo.setUserRecordTaskTimelines(list);
            return success(vo);
        } else {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("warn", "没有该任务详情,请检查");
            return ajaxResult;

        }

    }

    @Operation(summary = "获取任务派发userRecordTask详细信息-接收人详情页", description = "根据yesOrNot是Y（分解）|N（没有分解）判断按钮")
    @GetMapping(value = "/user/{taskId}")
    public AjaxResult getByUser(@PathVariable("taskId") Long taskId) {
        UserRecordTaskVO vo = userRecordTaskService.selectByTaskIdByUser(taskId, SecurityUtils.getUserId());

        List<UserRecordTask> userRecordTasks = userRecordTaskService.lambdaQuery().eq(UserRecordTask::getParentTaskId, taskId).eq(UserRecordTask::getInitiatorId, SecurityUtils.getUserId()).list();
        if (null != vo && null != userRecordTasks && userRecordTasks.size() > 0) {
            vo.setYesOrNot("Y");//显示两个按钮
            List<UserRecordTaskTimeline> list = userRecordTaskTimelineService.lambdaQuery().eq(UserRecordTaskTimeline::getTaskId, taskId).eq(UserRecordTaskTimeline::getDeleted, "0").list();
            vo.setUserRecordTaskTimelines(list);
            return success(vo);
        }

        if (null != vo && userRecordTasks.size() == 0) {
            vo.setYesOrNot("N");
            List<UserRecordTaskTimeline> list = userRecordTaskTimelineService.lambdaQuery().eq(UserRecordTaskTimeline::getTaskId, taskId).eq(UserRecordTaskTimeline::getDeleted, "0").list();
            vo.setUserRecordTaskTimelines(list);
            return success(vo);
        } else {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("warn", "接收人没有该任务,请检查!");
            return ajaxResult;
        }

    }

    @Operation(summary = "点击支线任务", description = "点击支线任务按钮:taskId-任务id")
    @GetMapping(value = "/level/{taskId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getTask(@PathVariable("taskId") Long taskId) {

//        List<UserRecordTask> list = userRecordTaskService.lambdaQuery().eq(UserRecordTask::getParentTaskId, taskId).eq(UserRecordTask::getDeleted, '0').list();
        List<UserRecordTaskVO> list = userRecordTaskService.selectX(taskId);

        for (UserRecordTaskVO userRecordTask : list) {
            //封装里边具体打卡反馈信息
            List<UserRecordTaskTimeline> listTimeline = userRecordTaskTimelineService.lambdaQuery().eq(UserRecordTaskTimeline::getTaskId, userRecordTask.getTaskId()).eq(UserRecordTaskTimeline::getDeleted, "0").list();
            userRecordTask.setUserRecordTaskTimelines(listTimeline);
        }
        return success(list);

    }

    @Operation(summary = "点击支线任务-具体个人", description = "点击支线任务按钮:taskId-任务id;userId 用户id")
    @GetMapping(value = "/levelUserId/taskId")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getLevelUserId(@RequestParam Long taskId, @RequestParam Long userId) {

//        UserRecordTask task = userRecordTaskService.lambdaQuery().eq(UserRecordTask::getTaskId, taskId).eq(UserRecordTask::getUserId, userId).eq(UserRecordTask::getDeleted, '0').one();
        UserRecordTaskVO task = userRecordTaskService.selectByTaskIdByUser(taskId, userId);
        if (null != task) {
            //封装里边具体打卡反馈信息
            List<UserRecordTaskTimeline> listTimeline = userRecordTaskTimelineService.lambdaQuery().eq(UserRecordTaskTimeline::getTaskId, task.getTaskId()).eq(UserRecordTaskTimeline::getDeleted, "0").list();
            task.setUserRecordTaskTimelines(listTimeline);
            return success(task);
        } else {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("warn", "接收人没有该任务,请检查!");
            return ajaxResult;
        }


    }

    // 任务详情 点击标记已读时间
    @Operation(summary = "任务已读", description = "标记已读:taskId-任务id")
    @PutMapping(value = "/read/{taskId}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getRead(@PathVariable("taskId") Long taskId) {
        // 取系统当前时间
//        String dateTimeNow = DateUtils.dateTimeNow();
        LocalDateTime dateTime = LocalDateTime.now(); // get the current date and time
        boolean update = userRecordTaskService.lambdaUpdate().set(UserRecordTask::getDateRead, dateTime).set(UserRecordTask::getHasRead, 'Y').eq(UserRecordTask::getTaskId, taskId).update();
        if (update) {
            return success();
        } else {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("warn", "请检查");
            return ajaxResult;
        }

    }


    /**
     * 新增任务派发userRecordTask
     */
    //@Log(title = "任务派发userRecordTask", businessType = BusinessType.INSERT)
    //@RequiresPermissions("emo:userRecordTask:add")
    @Operation(summary = "任务派发-新增", description = "任务分解点击提交按钮也是新增一个任务,新发起的任务默认level 是 1,任务分解level就是2,并且有父级任务id" +
            "任务状态 A_APPLIED(待接收) B_RECEIVED(待打卡) C_CHECKED_IN(待反馈) D_FEEDBACK_GIVEN(待评价) F_DONE(已结束) T_TIMED_OUT(超时)")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody UserRecordTaskVO vo) throws Exception{
        UserRecordTask userRecordTask = new UserRecordTask();
        BeanUtils.copyPropsIgnoreNull(vo, userRecordTask);
        if (null != vo.getParentTaskId()) {
            // 任务分解
            UserRecordTask byId = userRecordTaskService.getById(vo.getParentTaskId());
            String taskType = byId.getTaskType();
            if (!vo.getTaskType().equals(taskType)) {
                return AjaxResult.error("分解任务,任务类型不可修改");
            } else {
                userRecordTask.setCreateBy(SecurityUtils.getUsername());
                userRecordTask.setInitiatorId(SecurityUtils.getUserId());
                userRecordTask.setTaskId(null);
                userRecordTask.setTaskStatus("A_APPLIED");
                userRecordTask.setLevel(2);//是分解任务
                Assert.notNull(vo.getTaskContent(), "任务内容不能为空");
                Assert.notNull(vo.getUserId(), "交办对象不能为空");
                Assert.notNull(vo.getTaskType(), "任务类型不能为空");
                Assert.notNull(vo.getDateDeadline(), "任务结束时间不能为空");
                boolean save = userRecordTaskService.save(userRecordTask);
                if (save) {
                    //   创建任务成功之后 创建一个计时器,判断 有没有超时
                    userRecordTaskService.timedOut(userRecordTask);
                    return success();
                } else {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("warn", "任务分解失败!");
                    return ajaxResult;
                }
            }
        } else {
            userRecordTask.setCreateBy(SecurityUtils.getUsername());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            userRecordTask.setInitiatorId(SecurityUtils.getUserId());
            userRecordTask.setTaskStatus("A_APPLIED");
            userRecordTask.setLevel(1);//没有分解
            Assert.notNull(vo.getTaskContent(), "任务内容不能为空");
            Assert.notNull(vo.getUserId(), "交办对象不能为空");
            Assert.notNull(vo.getTaskType(), "任务类型不能为空");
            Assert.notNull(vo.getDateDeadline(), "任务结束时间不能为空");
            boolean save = userRecordTaskService.save(userRecordTask);
            if (save) {
                //  创建任务成功之后 创建一个计时器,判断 有没有超时
                userRecordTaskService.timedOut(userRecordTask);
                return success();
            } else {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("warn", "任务创建失败!");
                return ajaxResult;
            }

        }
    }

    @Operation(summary = "我发起的-评价", description = "新增评价,taskScore:星级;result :评价")
    @PostMapping("/addReview")
    public AjaxResult addReview(@RequestParam Long taskId, @RequestParam Integer taskScore, @RequestParam String result) {
        boolean update = userRecordTaskService.lambdaUpdate().eq(UserRecordTask::getTaskId, taskId).set(UserRecordTask::getTaskScore, taskScore)
                .set(UserRecordTask::getResult, result).set(UserRecordTask::getTaskStatus, "F_DONE").update();
        if (update) {
            return success();
        } else {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("warn", "修改失败!");
            return ajaxResult;
        }
    }

    /**
     * 修改任务派发userRecordTask
     */
    //@Log(title = "任务派发userRecordTask", businessType = BusinessType.UPDATE)
    //@RequiresPermissions("emo:userRecordTask:edit")
    @PutMapping("/edit")
    @Operation(summary = "修改任务", description = "修改任务派发userRecordTask ")
    public AjaxResult edit(@RequestBody UserRecordTaskVO vo) {
        UserRecordTask userRecordTask = new UserRecordTask();
        BeanUtils.copyPropsIgnoreNull(vo, userRecordTask);
        UserRecordTask one = userRecordTaskService.lambdaQuery().eq(UserRecordTask::getTaskId, vo.getTaskId()).one();
        if (null != one) {
            String taskStatus = one.getTaskStatus();
            if (!taskStatus.equals("A_APPLIED") && !taskStatus.equals("")) {
                //未接收,可以改
                return toAjax(userRecordTaskService.updateById(userRecordTask));
            } else {
                return AjaxResult.error("指派人已经接收,不可更改!");
            }
        }
        return AjaxResult.error("没有该任务!");
    }

    /**
     * 删除任务派发userRecordTask
     */
    //@Log(title = "任务派发userRecordTask", businessType = BusinessType.DELETE)
    //@RequiresPermissions("emo:userRecordTask:remove")
    @DeleteMapping("/{taskIds}")
    @Operation(summary = "删除任务", description = "删除任务,单独删除,批量删除")
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        for (Long taskId : taskIds) {
            boolean update = userRecordTaskService.lambdaUpdate().eq(UserRecordTask::getTaskId, taskId).set(UserRecordTask::getDeleted, '1').update();
            if (update) {
                userRecordTaskTimelineService.lambdaUpdate().eq(UserRecordTaskTimeline::getTaskId, taskId).set(UserRecordTaskTimeline::getDeleted, '1').update();
                continue;
            } else {
                return AjaxResult.error("删除失败!");
            }

        }
        return success();
    }
    //已经分解的任务接口

    @PostMapping("/listBrokenDown")
    @Operation(summary = "已经分解任务列表 ", description = "userNameOrTaskContent-姓名或者内容")
    public AjaxResult listBrokenDown(@RequestParam(required = false) String userNameOrTaskContent, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Long userId = SecurityUtils.getUserId();//当前登录用户

        Page<UserRecordTaskVO> list = userRecordTaskService.listBrokenDown(userNameOrTaskContent, userId, Page.of(current, size).addOrder(OrderItem.desc("task_id")));
        return success(list);
    }
}
